import { apiService } from './api';

// 组织架构相关类型定义
export interface Department {
  id: string;
  name: string;
  code: string;
  description?: string;
  parentId?: string;
  parentName?: string;
  fullPath: string;
  level: number;
  sortOrder: number;
  status: 'active' | 'inactive';
  managerId?: string;
  managerName?: string;
  managerAvatar?: string;
  memberCount: number;
  childCount: number;
  permissions: string[];
  settings: DepartmentSettings;
  contact: DepartmentContact;
  statistics: DepartmentStatistics;
  children?: Department[];
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  updatedBy: string;
}

export interface DepartmentSettings {
  allowSelfJoin: boolean;
  requireApproval: boolean;
  maxMembers?: number;
  inheritPermissions: boolean;
  visibilityLevel: 'public' | 'internal' | 'private';
  allowSubDepartments: boolean;
  autoAssignRoles: string[];
}

export interface DepartmentContact {
  email?: string;
  phone?: string;
  address?: string;
  location?: string;
  website?: string;
}

export interface DepartmentStatistics {
  totalMembers: number;
  activeMembers: number;
  managers: number;
  subDepartments: number;
  avgTenure: number;
  recentJoins: number;
  recentLeaves: number;
}

export interface DepartmentMember {
  id: string;
  userId: string;
  username: string;
  displayName: string;
  email: string;
  avatar?: string;
  position?: string;
  isManager: boolean;
  isPrimary: boolean;
  status: 'active' | 'inactive' | 'pending';
  joinedAt: string;
  assignedBy: string;
  roles: string[];
  permissions: string[];
}

export interface Position {
  id: string;
  name: string;
  code: string;
  description?: string;
  level: number;
  departmentId: string;
  departmentName: string;
  responsibilities: string[];
  requirements: string[];
  permissions: string[];
  salaryRange?: {
    min: number;
    max: number;
    currency: string;
  };
  isActive: boolean;
  maxCount?: number;
  currentCount: number;
  createdAt: string;
  updatedAt: string;
}

export interface OrganizationChart {
  departments: Department[];
  relationships: {
    parentId: string;
    childId: string;
    type: 'department' | 'position';
  }[];
  metadata: {
    totalDepartments: number;
    totalMembers: number;
    maxDepth: number;
    lastUpdated: string;
  };
}

export interface DepartmentSearchParams {
  keyword?: string;
  parentId?: string;
  level?: number;
  status?: Department['status'];
  managerId?: string;
  hasMembers?: boolean;
  memberCountRange?: {
    min: number;
    max: number;
  };
  createdRange?: {
    start: string;
    end: string;
  };
  page?: number;
  size?: number;
  sortBy?: 'name' | 'code' | 'level' | 'memberCount' | 'createdAt';
  sortOrder?: 'asc' | 'desc';
}

export interface CreateDepartmentRequest {
  name: string;
  code: string;
  description?: string;
  parentId?: string;
  managerId?: string;
  sortOrder?: number;
  settings?: Partial<DepartmentSettings>;
  contact?: Partial<DepartmentContact>;
  permissions?: string[];
}

export interface UpdateDepartmentRequest {
  name?: string;
  code?: string;
  description?: string;
  parentId?: string;
  managerId?: string;
  sortOrder?: number;
  status?: Department['status'];
  settings?: Partial<DepartmentSettings>;
  contact?: Partial<DepartmentContact>;
  permissions?: string[];
}

export interface DepartmentMemberAssignment {
  userId: string;
  position?: string;
  isManager?: boolean;
  isPrimary?: boolean;
  roles?: string[];
}

export interface DepartmentTransferRequest {
  userIds: string[];
  fromDepartmentId: string;
  toDepartmentId: string;
  keepRoles?: boolean;
  newPosition?: string;
  reason?: string;
}

export interface OrganizationImportData {
  departments: {
    name: string;
    code: string;
    description?: string;
    parentCode?: string;
    managerEmail?: string;
    settings?: Partial<DepartmentSettings>;
    contact?: Partial<DepartmentContact>;
  }[];
  members: {
    userEmail: string;
    departmentCode: string;
    position?: string;
    isManager?: boolean;
    isPrimary?: boolean;
  }[];
}

// 组织架构管理服务类
class OrganizationService {
  // 获取部门列表
  async getDepartments(params?: DepartmentSearchParams): Promise<{
    content: Department[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/organization/departments', params);
  }

  // 获取部门树形结构
  async getDepartmentTree(rootId?: string): Promise<Department[]> {
    return apiService.get('/organization/departments/tree', { rootId });
  }

  // 获取部门详情
  async getDepartment(id: string): Promise<Department> {
    return apiService.get(`/organization/departments/${id}`);
  }

  // 根据代码获取部门
  async getDepartmentByCode(code: string): Promise<Department> {
    return apiService.get(`/organization/departments/code/${code}`);
  }

  // 创建部门
  async createDepartment(departmentData: CreateDepartmentRequest): Promise<Department> {
    return apiService.post('/organization/departments', departmentData);
  }

  // 更新部门
  async updateDepartment(id: string, departmentData: UpdateDepartmentRequest): Promise<Department> {
    return apiService.put(`/organization/departments/${id}`, departmentData);
  }

  // 删除部门
  async deleteDepartment(id: string, transferToId?: string): Promise<void> {
    const params = transferToId ? `?transferToId=${transferToId}` : '';
    return apiService.delete(`/organization/departments/${id}${params}`);
  }

  // 移动部门
  async moveDepartment(id: string, newParentId?: string, newSortOrder?: number): Promise<Department> {
    return apiService.put(`/organization/departments/${id}/move`, {
      newParentId,
      newSortOrder
    });
  }

  // 复制部门结构
  async copyDepartment(id: string, newParentId?: string, newName?: string): Promise<Department> {
    return apiService.post(`/organization/departments/${id}/copy`, {
      newParentId,
      newName
    });
  }

  // 获取部门成员
  async getDepartmentMembers(departmentId: string, params?: {
    includeSubDepartments?: boolean;
    status?: DepartmentMember['status'];
    isManager?: boolean;
    page?: number;
    size?: number;
  }): Promise<{
    content: DepartmentMember[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get(`/organization/departments/${departmentId}/members`, params);
  }

  // 添加部门成员
  async addDepartmentMembers(departmentId: string, members: DepartmentMemberAssignment[]): Promise<void> {
    return apiService.post(`/organization/departments/${departmentId}/members`, { members });
  }

  // 移除部门成员
  async removeDepartmentMembers(departmentId: string, userIds: string[]): Promise<void> {
    return apiService.post(`/organization/departments/${departmentId}/members/remove`, { userIds });
  }

  // 更新部门成员信息
  async updateDepartmentMember(departmentId: string, userId: string, updates: {
    position?: string;
    isManager?: boolean;
    isPrimary?: boolean;
    roles?: string[];
  }): Promise<DepartmentMember> {
    return apiService.put(`/organization/departments/${departmentId}/members/${userId}`, updates);
  }

  // 设置部门负责人
  async setDepartmentManager(departmentId: string, userId: string): Promise<Department> {
    return apiService.put(`/organization/departments/${departmentId}/manager`, { userId });
  }

  // 移除部门负责人
  async removeDepartmentManager(departmentId: string): Promise<Department> {
    return apiService.delete(`/organization/departments/${departmentId}/manager`);
  }

  // 转移部门成员
  async transferMembers(request: DepartmentTransferRequest): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    return apiService.post('/organization/departments/transfer-members', request);
  }

  // 获取用户所属部门
  async getUserDepartments(userId: string): Promise<DepartmentMember[]> {
    return apiService.get(`/organization/users/${userId}/departments`);
  }

  // 获取部门路径
  async getDepartmentPath(departmentId: string): Promise<{
    id: string;
    name: string;
    code: string;
  }[]> {
    return apiService.get(`/organization/departments/${departmentId}/path`);
  }

  // 获取子部门
  async getSubDepartments(parentId: string, recursive?: boolean): Promise<Department[]> {
    return apiService.get(`/organization/departments/${parentId}/children`, { recursive });
  }

  // 获取部门统计
  async getDepartmentStatistics(departmentId?: string): Promise<DepartmentStatistics> {
    const url = departmentId 
      ? `/organization/departments/${departmentId}/statistics`
      : '/organization/statistics';
    return apiService.get(url);
  }

  // 获取组织架构图
  async getOrganizationChart(): Promise<OrganizationChart> {
    return apiService.get('/organization/chart');
  }

  // 搜索部门
  async searchDepartments(keyword: string, options?: {
    includeMembers?: boolean;
    maxResults?: number;
  }): Promise<Department[]> {
    return apiService.get('/organization/departments/search', {
      keyword,
      ...options
    });
  }

  // 检查部门代码是否可用
  async checkDepartmentCodeAvailability(code: string, excludeId?: string): Promise<{ available: boolean }> {
    return apiService.get('/organization/departments/check-code', { code, excludeId });
  }

  // 获取部门权限
  async getDepartmentPermissions(departmentId: string): Promise<string[]> {
    return apiService.get(`/organization/departments/${departmentId}/permissions`);
  }

  // 设置部门权限
  async setDepartmentPermissions(departmentId: string, permissions: string[]): Promise<void> {
    return apiService.put(`/organization/departments/${departmentId}/permissions`, { permissions });
  }

  // 继承父部门权限
  async inheritParentPermissions(departmentId: string): Promise<void> {
    return apiService.post(`/organization/departments/${departmentId}/inherit-permissions`);
  }

  // 职位管理
  async getPositions(departmentId?: string): Promise<Position[]> {
    return apiService.get('/organization/positions', { departmentId });
  }

  async createPosition(positionData: {
    name: string;
    code: string;
    description?: string;
    departmentId: string;
    level: number;
    responsibilities?: string[];
    requirements?: string[];
    permissions?: string[];
    salaryRange?: Position['salaryRange'];
    maxCount?: number;
  }): Promise<Position> {
    return apiService.post('/organization/positions', positionData);
  }

  async updatePosition(id: string, positionData: Partial<Position>): Promise<Position> {
    return apiService.put(`/organization/positions/${id}`, positionData);
  }

  async deletePosition(id: string): Promise<void> {
    return apiService.delete(`/organization/positions/${id}`);
  }

  // 导入组织架构
  async importOrganization(file: File, options?: {
    updateExisting?: boolean;
    createMissingUsers?: boolean;
    sendNotifications?: boolean;
  }): Promise<{
    departments: { success: number; failed: number; errors: string[] };
    members: { success: number; failed: number; errors: string[] };
  }> {
    const formData = new FormData();
    formData.append('file', file);
    if (options) {
      formData.append('options', JSON.stringify(options));
    }
    return apiService.post('/organization/import', formData);
  }

  // 导出组织架构
  async exportOrganization(params?: {
    format: 'csv' | 'excel' | 'json';
    includeMembers?: boolean;
    includeStatistics?: boolean;
    departmentIds?: string[];
  }): Promise<Blob> {
    return apiService.get('/organization/export', params);
  }

  // 批量操作
  async batchDepartmentOperation(operation: {
    type: 'activate' | 'deactivate' | 'delete' | 'move' | 'assign_permissions';
    departmentIds: string[];
    data?: any;
  }): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    return apiService.post('/organization/departments/batch', operation);
  }

  // 同步外部组织架构
  async syncExternalOrganization(config: {
    source: 'ldap' | 'ad' | 'api';
    endpoint: string;
    credentials: Record<string, any>;
    mapping: Record<string, string>;
    options: {
      createMissing?: boolean;
      updateExisting?: boolean;
      deleteRemoved?: boolean;
    };
  }): Promise<{
    departments: { created: number; updated: number; deleted: number };
    members: { created: number; updated: number; deleted: number };
    errors: string[];
  }> {
    return apiService.post('/organization/sync', config);
  }

  // 获取组织架构变更历史
  async getOrganizationHistory(params?: {
    departmentId?: string;
    userId?: string;
    action?: string;
    startDate?: string;
    endDate?: string;
    page?: number;
    size?: number;
  }): Promise<{
    content: {
      id: string;
      action: string;
      description: string;
      departmentId?: string;
      departmentName?: string;
      userId?: string;
      userName?: string;
      changes: Record<string, any>;
      performedBy: string;
      performedAt: string;
    }[];
    totalElements: number;
    totalPages: number;
    size: number;
    number: number;
  }> {
    return apiService.get('/organization/history', params);
  }

  // 验证组织架构完整性
  async validateOrganization(): Promise<{
    isValid: boolean;
    issues: {
      type: 'circular_reference' | 'orphaned_department' | 'missing_manager' | 'permission_conflict';
      departmentId: string;
      departmentName: string;
      description: string;
      severity: 'error' | 'warning';
    }[];
  }> {
    return apiService.get('/organization/validate');
  }

  // 修复组织架构问题
  async fixOrganizationIssues(fixes: {
    type: string;
    departmentId: string;
    action: 'auto_fix' | 'manual_fix';
    data?: any;
  }[]): Promise<{
    fixed: number;
    failed: number;
    errors: string[];
  }> {
    return apiService.post('/organization/fix', { fixes });
  }
}

export const organizationService = new OrganizationService();
export default organizationService;